import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

public class PushClient {

    public static void main(String[] args) throws IOException {
        new PushClient();
    }

    private String user = "merchant11223345";
    private String host = "47.112.117.182";
    private int port = 8888;
    private Socket socket;

    public PushClient() throws IOException {
        start();
    }

    private void start() {
        new Thread(() -> {
            while (true) {
                try {
                    socket = new Socket(host, port);
                    new PrintWriter(socket.getOutputStream(), true).println("login:" + user);
                    // TODO 心跳
                    readMsg();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    System.out.println("断开链接");
                    try {
                        socket.close();
                    } catch (IOException e) {
                    }
                }
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                }
            }
        }).start();

    }

    private void readMsg() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line;
        while (!Objects.equals(line = br.readLine(), "close")) {
            if (line == null) {
                continue;
            }
            System.out.println("收到客户端消息" + line);
            PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
            if (Objects.equals("", line)) {
                // 心跳
                pw.println("心跳");
            }
        }
    }
}
